package com.jse.util.concurrent.new1.executor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

public class ThreadPoolExecutorTest {
	
	/**
	 * 获取多核数量
	 */
	@Test
	public void testProcessor() {
		int i = Runtime.getRuntime().availableProcessors();
		System.out.println(i);
	}
	
	@Test
	public void testSubmit() throws Exception {
		ExecutorService executor = Executors.newCachedThreadPool();
		Future<Boolean> future = executor.submit(new Task(), true);
		System.out.println(future.get());
	}
	
	/**
	 * 线程泄露，发生异常线程逐步减少，最后为0，
	 */
	@Test
	public void testException() {
		ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
		executor.execute(new Runnable() {
			@Override
			public void run() {
				throw new RuntimeException();
			}
		});
	}

	@Test
	public void testShutdown() throws Exception {
		ExecutorService executor = Executors.newCachedThreadPool();
		executor.execute(new Runnable() {
			@Override
			public void run() {
				try {
					Thread.sleep(2000);
					System.out.println("This is Anonymous Class");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
		executor.shutdown();
		Thread.sleep(4000);
		//抛出RejectedExecutionException
		executor.execute(new Task());
	}
}

class Task implements Runnable {
	
	@Override
	public void run() {
		System.out.println("This is Task");
	}
}
